<script setup lang="ts">
import type { PlusColumn } from 'plus-pro-components'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'

import {
    loginLogExport,
    useGetLoginList,
    useLoginLogClean,
    useLoginLogDdeletIds,
    useLoginLogUnlock,
} from '@fl/api/joint-api'
import { SearchForm, SearchTable } from '@fl/components'
import { useMessage } from '@fl/hooks/web/use-message'
import { formatTime } from '@fl/utils'
import { cloneDeep } from 'lodash-es'
import { reactive, ref } from 'vue'

import { useDicts } from '../hooks/dict'

const { createConfirmModal, createMessage } = useMessage()
const tableRef = ref()

const { dicts, getDictLabel } = useDicts()

type IState = {
    ipaddr: string
    status: string
    timeRange?: any
    userName: string
}
const initialState = {
    ipaddr: '',
    status: '',
    timeRange: [],
    userName: '',
}
const state = ref<IState>(cloneDeep(initialState))

const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}
const tablePage = ref(cloneDeep(initialPage))
const param = computed(() => ({
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
    ipaddr: state.value.ipaddr,
    status: state.value.status,
    loginName: state.value.userName,
    startTime: state.value.timeRange?.[0]
        ? formatTime(state.value?.timeRange?.[0], 'yyyy-MM-dd 00:00:00')
        : '',
    endTime: state.value.timeRange?.[1]
        ? formatTime(state.value?.timeRange?.[1], 'yyyy-MM-dd 00:00:00')
        : '',

}))
const { data, isLoading } = useGetLoginList(param)
const { mutate: deleteMutateIds } = useLoginLogDdeletIds()
// const { mutate: unlockMutate } = useLoginLogUnlock()
const { mutate: cleanMutate } = useLoginLogClean()
const records = ref()
const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

watchEffect(() => {
    if (data.value) {
        records.value = cloneDeep(data.value.records)
        tablePage.value.total = data.value.total!
    }
})
// 搜索
function submit(values) {
    state.value = { ...values }
    tablePage.value.currentPage = 1
}
function reset() {
    state.value = cloneDeep(initialState)
    tablePage.value = cloneDeep(initialPage)
}
const columns: PlusColumn[] = [
    {
        label: '登录地址',
        prop: 'ipaddr',
    },
    {
        label: '用户名称',
        prop: 'loginName',
    },
    {
        label: '状态',
        options: dicts.loginStatusOption,
        prop: 'status',
        valueType: 'select',
    },
    {
        fieldProps: {
            'endPlaceholder': '结束时间',
            'startPlaceholder': '开始时间',
            'type': 'daterange',
            'value-format': 'YYYY-MM-DD',
        },
        label: '操作时间',
        prop: 'timeRange',
        valueType: 'date-picker',
    },
]
const gridOptions = reactive<VxeGridProps>({
    columns: [
        { type: 'checkbox', width: 50 },
        { field: 'id', title: '访问编号' },
        { field: 'loginName', title: '用户名称' },
        { field: 'ipaddr', title: '登陆地址' },
        { field: 'loginLocation', title: '登录地点' },
        { field: 'browser', title: '浏览器' },
        { field: 'os', title: '操作系统' },
        { field: 'status', slots: { default: 'status' }, title: '登陆状态' },
        { field: 'msg', title: '操作信息' },
        { field: 'loginTime', title: '登录日期' },
        // { slots: { default: 'operate' }, title: '操作' },

    ],
})
// 批量删除
function goMultipleDelete() {
    const $table = tableRef.value?.tableInstance
    if ($table) {
        const selectRecords = $table.getCheckboxRecords()
        const ids = selectRecords.map(item => item.id)
        if (selectRecords.length) {
            createConfirmModal({
                content: '是否确认删除？',
                onError: () => {
                    console.log('操作取消！')
                },
                onSuccess: () => {
                    deleteMutateIds(ids, {
                        onSuccess: () => {
                            createMessage.success('删除成功')
                        },
                    })
                },
            })
        }
        else {
            createMessage.warning('请至少选择一条数据')
        }
    }
}

// 清空
function cleanLog() {
    createConfirmModal({
        content: '是否确认清空？',
        onError: () => {
            console.log('操作取消！')
        },
        onSuccess: async () => {
            const res = await cleanMutate()
            if (res) {
                createMessage.success('清空成功')
            }
        },
    })
}

async function exportExcel() {
    const result = await loginLogExport({ ...unref(param), pageSize: 1000000 })
    const blob = new Blob([result], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const objectUrl = URL.createObjectURL(blob)
    location.href = objectUrl
    URL.revokeObjectURL(objectUrl)
}

// 解锁
// function unLock(row) {
//     createConfirmModal({
//         content: `是否确认解锁用户"${row.userName}"数据项`,
//         onError: () => {
//             console.log('操作取消！')
//         },
//         onSuccess: () => {
//             unlockMutate(row.userName, {
//                 onSuccess: () => {
//                     createMessage.success('操作成功')
//                 },
//             })
//         },
//     })
// }
</script>

<template>
    <ElCard class="mb-20"
            shadow="never"
    >
        <SearchForm v-bind="state"
                    :columns="columns"
                    submit-text="搜索"
                    @reset="reset"
                    @submit="submit"
        />
    </ElCard>

    <ElCard shadow="never">
        <SearchTable ref="tableRef"
                     v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :loading="isLoading"
                     :data="records"
                     @page-change="handlePageChange"
        >
            <template #toolbar_buttons>
                <ElButton @click="goMultipleDelete">
                    删除
                </ElButton>

                <ElButton @click="cleanLog">
                    清空
                </ElButton>

                <ElButton @click="exportExcel">
                    导出
                </ElButton>
            </template>

            <template #status="{ row }">
                <el-tag :type="row.status == 0 ? 'primary' : 'danger'">
                    {{ getDictLabel("loginStatusOption", row.status) }}
                </el-tag>
            </template>

            <!-- <template #operate="{ row }">
                <el-button type="text"
                           @click="unLock(row)"
                >
                    解锁
                </el-button>
            </template> -->
        </SearchTable>
    </ElCard>
</template>
